require "http/client"
require "json"

BLNS_JSON_RAW_URL = "https://raw.githubusercontent.com/minimaxir/big-list-of-naughty-strings/master/blns.json"
BLNS_FILE_PATH    = "spec/blns.cr"

response = HTTP::Client.get BLNS_JSON_RAW_URL
json = Array(String).from_json(response.body)

blns_content = String::Builder.new
blns_content << <<-EOS
# ameba:disable Lint/Formatting
# GENERATED FILE. DO NOT EDIT.
#
# This file was generated from big-list-of-naughty-strings' JSON file:
# #{BLNS_JSON_RAW_URL}
# at #{Time.utc} by the script, tools/update_blns.cr.
\n
EOS

blns_content.puts "module BLNS"
blns_content.puts "  def self.each(& : String ->) : Nil"
blns_content.puts "    @@list.each { |element| yield element }"
blns_content.puts "  end"
blns_content.puts
blns_content.puts "  def self.size : Int32"
blns_content.puts "    @@list.size"
blns_content.puts "  end"
blns_content.puts
blns_content.puts "  @@list : Array(String) = ["

json.each do |str|
  escaped = str.gsub("\\", "\\\\")
    .gsub('"', "\\\"")
    .gsub("\#", "\\#")
  blns_content.puts "    \"#{escaped}\","
end

blns_content.puts "  ]" # end of @@list
blns_content.puts "end" # module BLNS

File.write(BLNS_FILE_PATH, blns_content.to_s)
